<?php

namespace app\controller;

use app\model\DistributionOfficerModel;
use app\model\MemberModel;
use app\service\MemberService;
use app\service\MiniProgramService;
use app\service\SmsService;
use app\validate\MemberValidate;
use EasyWeChat\Factory;
use support\facade\Logger;
use Tinywan\Jwt\JwtToken;
use xy_jx\Utils\Encryption;
use const support\AUTH_CODE_NO;
use const support\CORRECT;
use const support\ERROR;
use const support\PARAMETER_ERROR;
use const support\share_common_info;
use const support\SMS_EXPIRE_ERROR;
use const support\SMS_REQUEST_SEND_ERROR;
use const support\SMS_SCENE_LOGIN;
use const support\SMS_VERIFY_ERROR;
use const support\SMS_VERIFY_TIMES_ERROR;
use const support\SUCCESS;
use const support\THIRD_OAUTH_TYPE_1;
use const support\USER_UNBIND_MOBILE;
use const support\USER_UNBIND_OAUTH;

class MemberController
{

    //小程序登录
    public function miniProgramLogin(): \support\Response
    {
        try {
            //接收前端参数
            $params=getRequestData([
                'jscode',
                'invite_code'
            ]);
            MemberValidate::toCheck('miniProgramLogin',$params);
            //获取微信openid
            $openid=MiniProgramService::getMemberOpenid($params['jscode']);
            if (!$openid){
                return buildFail(PARAMETER_ERROR,'授权码已失效');
            }
            //存在销售码
            $pid=0;
            if (!empty($params['invite_code'])){
                $pid=MemberModel::where('member_sn',$params['invite_code'])->where('status',CORRECT)->value('id')?:0;
            }
            Logger::app('小程序登录：销售ID','info',$pid);
            //第三方授权登录
            list($memberId,$memberThirdOauthId)=MemberService::thirdLoginOrRegister(THIRD_OAUTH_TYPE_1,$openid,$pid);
            if (empty($memberId)){
                //加密第三方授权ID
                $thirdOauthEncrypt = Encryption::encrypt([
                    'member_third_oauth_id'=>$memberThirdOauthId,
                    'pid'                  =>$pid
                ]);
                if (!MiniProgramService::checkNicknameAndAvatarPerfect($memberThirdOauthId)){
                    $config=config('wechat.wechat_official');
                    Logger::app('小程序登录：公众号配置','info',$config);
//                    $app = Factory::officialAccount($config);
                    //重定向地址
                    $redirectUrl=sprintf("%s/h5/memberWechatOauth/%s",env('APP_URL'),$memberThirdOauthId);
                    Logger::app('小程序登录：重定向地址','info',[$redirectUrl]);
                    $oauthUrl=sprintf('https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&&state=STATE#wechat_redirect',$config['app_id'],urlencode($redirectUrl));
                    Logger::app('小程序登录：授权地址','info',[$oauthUrl]);
                    return buildFail(USER_UNBIND_OAUTH,'待授权用户信息',[
                        'third_oauth_encrypt'   =>$thirdOauthEncrypt,
                        'oauth_url'             =>$oauthUrl,
                        'openid'                =>$openid,
                        'share_common_info'     =>share_common_info
                    ]);
                }
                return buildFail(USER_UNBIND_MOBILE,'待绑定用户手机号',[
                    'third_oauth_encrypt'=>$thirdOauthEncrypt,
                    'openid'                =>$openid,
                    'share_common_info'     =>share_common_info
                ]);
            }
            $tokeData=[
                'id'	    =>$memberId
            ];
            //查询该用户唯一标识
            $inviteCode=MemberModel::where([
                'id'=>$memberId
            ])->value('member_sn')?:"";
            return buildSuccess([
                'token'             =>JwtToken::generateToken($tokeData),
                'openid'            =>$openid,
                'invite_code'       =>$inviteCode,
                'share_common_info' =>share_common_info
            ]);
        }catch (\Throwable $e){
            return buildFail(ERROR,$e->getMessage());
        }
    }

    //手机号注册
    public function quickLogin(): \support\Response
    {
        //接收前端传参
        $params=getRequestData([
            'mobile'	=>'',
            'code'	    =>'',
            'third_oauth'=>'',
            'invite_code' =>''
        ]);
        //进行校验
        MemberValidate::toCheck('quickLogin',$params);
        try {
            //验证码校验
            $code=SmsService::getSmsCode(SMS_SCENE_LOGIN,$params['mobile']);
            Logger::app('注册或登录操作:验证码校验1','info',[$code]);
            if (!$code){
                return buildFail(SMS_EXPIRE_ERROR);
            }
            Logger::app('注册或登录操作:验证码校验2','info',[$code,$params['code']]);
            if ($code!==$params['code']){
                return buildFail(SMS_VERIFY_ERROR);
            }
            //存在销售码
            $pid=0;
            if (!empty($params['invite_code'])){
                $pid=MemberModel::where('member_sn',$params['invite_code'])->where('status',CORRECT)->value('id')?:0;
                Logger::app('注册或登录操作:用户存在情况','info',[$pid]);
                if($pid){
                    //检测该用户是否是分销官，不是的话无绑定下级权限
                    $pid=DistributionOfficerModel::where([
                        'member_id'=>$pid,
                        'status'   =>CORRECT
                    ])->value('member_id')?:0;
                    Logger::app('注册或登录操作:分销官过滤情况','info',[$pid]);
                }
            }
            //解密三方授权信息
            $memberThirdOauthId=0;
            $thirdOauthPid=0;
            if (!empty($params['third_oauth'])){
                $thirdOauthDecrypt = Encryption::decrypt($params['third_oauth']);
                Logger::app('注册或登录操作:解密三方授权信息','info',[$thirdOauthDecrypt]);
                $memberThirdOauthId=$thirdOauthDecrypt['member_third_oauth_id']??0;
                $thirdOauthPid=$thirdOauthDecrypt['pid']??0;
            }
            //最终决定使用邀请人ID
            $pid=!empty($pid)?$pid:$thirdOauthPid;
            //快捷登录服务
            $memberId=MemberService::UserLoginOrRegister($params['mobile'],$memberThirdOauthId,$pid);
            Logger::app('注册或登录操作:快捷登录服务','info',[$memberId]);
            if (!$memberId){
                return buildFail(AUTH_CODE_NO);
            }
            //移除短信验证码缓存记录
            SmsService::removeSmsCode(SMS_SCENE_LOGIN,$params['mobile']);
            $tokeData=[
                'id'	    =>$memberId
            ];
            return buildSuccess([
                'token'=>JwtToken::generateToken($tokeData)
            ]);
        }catch (\Throwable $e){
            return buildFail(ERROR,$e->getMessage());
        }
    }

    //发送短信验证码
    public function sendSms(): \support\Response
    {
        //接收前端传参
        $params=getRequestData([
            'mobile'	=>'',
            'scene'     =>SMS_SCENE_LOGIN
        ]);
        //进行校验
        MemberValidate::toCheck('sendSmsCode',$params);
        try {
            //检测是否已发送
            $code=SmsService::getSmsCode(SMS_SCENE_LOGIN,$params['mobile']);
            if ($code){
                return buildFail(SMS_VERIFY_TIMES_ERROR);
            }
            //未发送则发送新短信
            $ret=SmsService::sendSmsCode($params['scene'],$params['mobile']);
            if (!$ret){
                return buildFail(SMS_REQUEST_SEND_ERROR);
            }
            return buildSuccess();
        }catch (\Throwable $e){
            return buildFail(ERROR,$e->getMessage());
        }
    }

    //个人中心
    public function userCenter(): \support\Response
    {
        try {
            $data=MemberService::getUserCenter(getMemberId());
            return buildSuccess($data);
        }catch (\Throwable $e){
            return buildFail(ERROR,$e->getMessage());
        }
    }

    //解除绑定关系
    public static function unbindRelationship(): \support\Response
    {
        //接收前端传参
        $params=getRequestData([
            'openid'	=>''
        ]);
        try {
            MemberService::toUnbindRelationship($params['openid']);
            return buildSuccess();
        }catch (\Throwable $e){
            return buildFail(ERROR,$e->getMessage());
        }
    }


}